use std::error::Error;
use std::{fs, io};
use std::fs::File;
use std::io::Read;
use anyhow::anyhow;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE;
use base64::prelude::BASE64_STANDARD;
// use serde_yml::Value::String;

use crate::opts::{Base64Format, BaseType};
use crate::opts::Base64Format::*;
use crate::read_from_file_or_console;

pub fn base64_process(base_type: BaseType, format: Base64Format, data: String) -> anyhow::Result<String> {
    println!("base_type is {:?} , sign is {}", base_type, data);
    match base_type {
        BaseType::Decode => {
            decode(format, data)
        }

        BaseType::Encode => {
            encode(format, data)
        }
    }
}


fn encode(format: Base64Format, data: String) -> anyhow::Result<String> {
    let mut res = read_from_file_or_console("请输入需要编码的字符:".to_string(), data);

    match format {
        Base64Format::STANDARD => {
            res = BASE64_STANDARD.encode(res);
        }
        Base64Format::URL => {
            res = URL_SAFE.encode(res);
        }
    }

    Ok(res)
}


fn decode(format: Base64Format, data: String) -> anyhow::Result<String> {
    let mut str = read_from_file_or_console("请输入需要解码的字符:".to_string(), data);

    let mut res = Vec::new();

    match format {
        Base64Format::STANDARD => {
            res = BASE64_STANDARD.decode(str)?;
        }
        Base64Format::URL => {
            res = URL_SAFE.decode(str)?;
        }
    }

    let res = String::from_utf8(res)?;
    Ok(res)
}